import React, { useState } from 'react';
import { Card, Row, Col, Statistic, Space, Typography, Tag, Progress, Divider, Button } from 'antd';
import {
  DatabaseOutlined,
  GitlabOutlined,
  FileTextOutlined,
  CodeOutlined,
  BranchesOutlined,
  CheckCircleOutlined,
  TableOutlined,
  ApartmentOutlined,
  SettingOutlined,
  GlobalOutlined,
  BugOutlined,
  WarningOutlined
} from '@ant-design/icons';
import { EnhancedScanTaskResponse } from '../../types/taskDetail';
import SqlStatementsModal from './SqlStatementsModal';
import { TaskScanResults } from '../../services/api';
import './TaskStatistics.css';

const { Text, Title } = Typography;

interface TaskStatisticsProps {
  task: EnhancedScanTaskResponse;
  scanResults?: TaskScanResults | null; // 新增：扫描结果数据
}

const TaskStatistics: React.FC<TaskStatisticsProps> = ({ task, scanResults }) => {
  const [sqlModalVisible, setSqlModalVisible] = useState(false);
  
  // 计算问题统计
  const calculateProblemStats = () => {
    if (!scanResults || !scanResults.issues) {
      return { totalProblems: 0, problemSqlCount: 0, problemRate: 0 };
    }
    
    const issues = scanResults.issues;
    const totalProblems = issues.length;
    // 使用后端返回的problemSqlStatements字段，而不是前端计算
    const problemSqlCount = scanResults.problemSqlStatements || 0; // 有问题的SQL数量
    const totalSqlCount = scanResults.sqlStatements || 0; // 总SQL数量
    const problemRate = totalSqlCount > 0 ? (problemSqlCount / totalSqlCount) * 100 : 0; // 问题率 = 有问题SQL / 总SQL
    
    return { totalProblems, problemSqlCount, problemRate };
  };

  const problemStats = calculateProblemStats();
  
  // 从extractionStats中解析统计信息
  const parseStatistics = () => {
    const extractionStats = task.extractionStats || {};
    
    // 根据任务类型返回对应的统计信息组件
    switch (task.taskType) {
      case 'GIT_SCAN':
        return renderGitStatistics(extractionStats);
      case 'DATABASE_SCAN':
        return renderDatabaseStatistics(extractionStats);
      case 'MIXED_SCAN':
        return renderMixedStatistics(extractionStats);
      default:
        return renderDefaultStatistics(extractionStats);
    }
  };

  // 渲染Git扫描统计
  const renderGitStatistics = (stats: any) => {
    const config = task.config || {};
    
    return (
      <>
        <Row gutter={[16, 16]}>
          <Col xs={24} lg={8}>
            <Card
              title={
                <Space>
                  <BranchesOutlined style={{ color: '#52c41a' }} />
                  <span>仓库基本信息</span>
                </Space>
              }
              className="statistics-card git-card"
              size="small"
            >
              <div className="stat-item">
                <Text type="secondary">Git平台</Text>
                <div>
                  <Tag color="green" icon={<GitlabOutlined />}>
                    {config.gitPlatform || 'GitLab'}
                  </Tag>
                </div>
              </div>
              
              <div className="stat-item">
                <Text type="secondary">目标分支</Text>
                <div>
                  <Tag color="blue" icon={<BranchesOutlined />}>
                    {task.branchName || 'main'}
                  </Tag>
                </div>
              </div>
              
              <div className="stat-item">
                <Text type="secondary">仓库地址</Text>
                <div>
                  <Text code style={{ fontSize: 11, wordBreak: 'break-all' }}>
                    {config.gitRepoUrl ? 
                      config.gitRepoUrl.length > 40 ? 
                        `${config.gitRepoUrl.substring(0, 40)}...` : 
                        config.gitRepoUrl
                      : '未配置'
                    }
                  </Text>
                </div>
              </div>
            </Card>
          </Col>

          <Col xs={24} lg={8}>
            <Card
              title={
                <Space>
                  <CodeOutlined style={{ color: '#1890ff' }} />
                  <span>代码扫描统计</span>
                </Space>
              }
              className="statistics-card scan-card"
              size="small"
            >
              <Row gutter={16}>
                <Col span={12}>
                  <div className="clickable-statistic" onClick={() => setSqlModalVisible(true)}>
                    <Statistic
                      title={
                        <Space>
                          <span>SQL语句数</span>
                          <Button 
                            type="link" 
                            size="small" 
                            style={{ padding: 0, height: 'auto' }}
                          >
                            点击查看详情
                          </Button>
                        </Space>
                      }
                      value={stats.totalStatements || 0}
                      prefix={<FileTextOutlined />}
                      valueStyle={{ fontSize: 20, color: '#1890ff', cursor: 'pointer' }}
                    />
                  </div>
                </Col>
                <Col span={12}>
                  <Statistic
                    title="有问题SQL"
                    value={problemStats.problemSqlCount}
                    prefix={<BugOutlined />}
                    valueStyle={{ 
                      fontSize: 20, 
                      color: problemStats.problemSqlCount > 0 ? '#ff4d4f' : '#52c41a' 
                    }}
                  />
                </Col>
              </Row>
              
              <Divider style={{ margin: '12px 0' }} />
              
              <div className="stat-item">
                <Text type="secondary">匹配规则数</Text>
                <div>
                  <Text strong>{stats.rulesMatched || 0}</Text>
                </div>
              </div>
              
              <div className="stat-item">
                <Text type="secondary">问题率</Text>
                <div>
                  <Progress 
                    percent={Math.round(problemStats.problemRate)} 
                    size="small" 
                    strokeColor={
                      problemStats.problemRate > 20 ? '#ff4d4f' :
                      problemStats.problemRate > 10 ? '#faad14' : '#52c41a'
                    }
                    format={(percent) => `${percent}%`}
                  />
                </div>
              </div>
            </Card>
          </Col>

          <Col xs={24} lg={8}>
            <Card
              title={
                <Space>
                  <FileTextOutlined style={{ color: '#fa8c16' }} />
                  <span>文件处理统计</span>
                </Space>
              }
              className="statistics-card file-card"
              size="small"
            >
              <div className="stat-item">
                <Text type="secondary">总文件数</Text>
                <div>
                  <Statistic
                    value={stats.totalFiles || 0}
                    valueStyle={{ fontSize: 24, color: '#fa8c16', fontWeight: 'bold' }}
                  />
                </div>
              </div>
              
              <Divider style={{ margin: '12px 0' }} />
              
              <div className="file-distribution">
                <div className="file-type-item">
                  <Tag color="blue">.sql</Tag>
                  <Text>{stats.sqlFiles || 0} 个</Text>
                </div>
                <div className="file-type-item">
                  <Tag color="green">.java</Tag>
                  <Text>{stats.javaFiles || 0} 个</Text>
                </div>
                <div className="file-type-item">
                  <Tag color="orange">.xml</Tag>
                  <Text>{stats.xmlFiles || 0} 个</Text>
                </div>
              </div>
              
              <div className="stat-item">
                <Text type="secondary">扫描覆盖率</Text>
                <Progress 
                  percent={Math.round((stats.scannedFiles / (stats.totalFiles || 1)) * 100)} 
                  size="small" 
                  status="active"
                  strokeColor="#52c41a"
                />
              </div>
            </Card>
          </Col>
        </Row>
      </>
    );
  };

  // 渲染数据库扫描统计
  const renderDatabaseStatistics = (stats: any) => {
    const config = task.config || {};
    const dbInfo = stats.databaseInfo || {};
    const objectCounts = stats.objectCounts || {};
    
    return (
      <>
        <Row gutter={[16, 16]}>
          <Col xs={24} lg={8}>
            <Card
              title={
                <Space>
                  <DatabaseOutlined style={{ color: '#fa8c16' }} />
                  <span>数据库连接信息</span>
                </Space>
              }
              className="statistics-card database-card"
              size="small"
            >
              <div className="stat-item">
                <Text type="secondary">数据库类型</Text>
                <div>
                  <Tag color="orange" icon={<DatabaseOutlined />}>
                    {dbInfo.dbType || config.databaseType || 'MYSQL'}
                  </Tag>
                </div>
              </div>
              
              <div className="stat-item">
                <Text type="secondary">版本信息</Text>
                <div>
                  <Text code>{dbInfo.dbVersion || '未知'}</Text>
                </div>
              </div>
              
              <div className="stat-item">
                <Text type="secondary">连接地址</Text>
                <div>
                  <Text code style={{ fontSize: 11 }}>
                    {dbInfo.host || config.databaseHost}:{dbInfo.port || config.databasePort}
                  </Text>
                </div>
              </div>
              
              <div className="stat-item">
                <Text type="secondary">目标数据库</Text>
                <div>
                  <Tag color="blue" icon={<GlobalOutlined />}>
                    {dbInfo.database || config.databaseName}
                  </Tag>
                </div>
              </div>
            </Card>
          </Col>

          <Col xs={24} lg={8}>
            <Card
              title={
                <Space>
                  <TableOutlined style={{ color: '#1890ff' }} />
                  <span>DDL提取统计</span>
                </Space>
              }
              className="statistics-card extraction-card"
              size="small"
            >
              <Row gutter={16}>
                <Col span={12}>
                  <div className="clickable-statistic" onClick={() => setSqlModalVisible(true)}>
                    <Statistic
                      title={
                        <Space>
                          <span>DDL语句</span>
                          <Button 
                            type="link" 
                            size="small" 
                            style={{ padding: 0, height: 'auto' }}
                          >
                            点击查看详情
                          </Button>
                        </Space>
                      }
                      value={stats.totalStatements || 0}
                      prefix={<FileTextOutlined />}
                      valueStyle={{ fontSize: 20, color: '#1890ff', cursor: 'pointer' }}
                    />
                  </div>
                </Col>
                <Col span={12}>
                  <Statistic
                    title="有问题SQL"
                    value={problemStats.problemSqlCount}
                    prefix={<BugOutlined />}
                    valueStyle={{ 
                      fontSize: 20, 
                      color: problemStats.problemSqlCount > 0 ? '#ff4d4f' : '#52c41a' 
                    }}
                  />
                </Col>
              </Row>
              
              <Divider style={{ margin: '12px 0' }} />
              
              <div className="stat-item">
                <Text type="secondary">问题率</Text>
                <div>
                  <Progress 
                    percent={Math.round(problemStats.problemRate)} 
                    size="small" 
                    strokeColor={
                      problemStats.problemRate > 20 ? '#ff4d4f' :
                      problemStats.problemRate > 10 ? '#faad14' : '#52c41a'
                    }
                    format={(percent) => `${percent}%`}
                  />
                </div>
              </div>
              
              <div className="ddl-breakdown">
                <div className="ddl-type-item">
                  <Tag color="blue">CREATE</Tag>
                  <Text>{stats.createStatements || 0}</Text>
                </div>
                <div className="ddl-type-item">
                  <Tag color="orange">ALTER</Tag>
                  <Text>{stats.alterStatements || 0}</Text>
                </div>
                <div className="ddl-type-item">
                  <Tag color="red">DROP</Tag>
                  <Text>{stats.dropStatements || 0}</Text>
                </div>
              </div>
            </Card>
          </Col>

          <Col xs={24} lg={8}>
            <Card
              title={
                <Space>
                  <ApartmentOutlined style={{ color: '#722ed1' }} />
                  <span>对象分析统计</span>
                </Space>
              }
              className="statistics-card object-card"
              size="small"
            >
              <Row gutter={[8, 12]}>
                <Col span={12}>
                  <div className="object-stat-item">
                    <div className="object-count">{objectCounts['表'] || objectCounts['tables'] || 0}</div>
                    <div className="object-label">数据表</div>
                  </div>
                </Col>
                <Col span={12}>
                  <div className="object-stat-item">
                    <div className="object-count">{objectCounts['索引'] || objectCounts['indexes'] || 0}</div>
                    <div className="object-label">索引</div>
                  </div>
                </Col>
                <Col span={12}>
                  <div className="object-stat-item">
                    <div className="object-count">{objectCounts['视图'] || objectCounts['views'] || 0}</div>
                    <div className="object-label">视图</div>
                  </div>
                </Col>
                <Col span={12}>
                  <div className="object-stat-item">
                    <div className="object-count">{objectCounts['存储过程'] || objectCounts['procedures'] || 0}</div>
                    <div className="object-label">存储过程</div>
                  </div>
                </Col>
              </Row>
              
              <Divider style={{ margin: '12px 0' }} />
              
              <div className="stat-item">
                <Text type="secondary">内容大小</Text>
                <div>
                  <Text strong>
                    {stats.totalContentSize ? `${(stats.totalContentSize / 1024).toFixed(1)} KB` : '--'}
                  </Text>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
      </>
    );
  };

  // 渲染混合扫描统计
  const renderMixedStatistics = (stats: any) => {
    const gitStats = stats.git || {};
    const dbStats = stats.database || {};
    
    return (
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={8}>
          <Card
            title={
              <Space>
                <GitlabOutlined style={{ color: '#52c41a' }} />
                <span>Git部分统计</span>
              </Space>
            }
            className="statistics-card git-mixed-card"
            size="small"
          >
            <div className="clickable-statistic" onClick={() => setSqlModalVisible(true)}>
              <Statistic
                title={
                  <Space>
                    <span>SQL语句数</span>
                    <Button 
                      type="link" 
                      size="small" 
                      style={{ padding: 0, height: 'auto' }}
                    >
                      点击查看详情
                    </Button>
                  </Space>
                }
                value={gitStats.totalSqlStatements || 0}
                prefix={<FileTextOutlined />}
                valueStyle={{ fontSize: 18, color: '#52c41a', cursor: 'pointer' }}
              />
            </div>
            
            <div className="stat-item">
              <Text type="secondary">文件数量</Text>
              <div>
                <Text strong>{gitStats.totalFiles || 0} 个</Text>
              </div>
            </div>
            
            <div className="stat-item">
              <Text type="secondary">处理状态</Text>
              <div>
                <Tag color="green" icon={<CheckCircleOutlined />}>
                  {gitStats.completed ? '完成' : '处理中'}
                </Tag>
              </div>
            </div>
          </Card>
        </Col>

        <Col xs={24} lg={8}>
          <Card
            title={
              <Space>
                <DatabaseOutlined style={{ color: '#fa8c16' }} />
                <span>数据库部分统计</span>
              </Space>
            }
            className="statistics-card db-mixed-card"
            size="small"
          >
            <div className="clickable-statistic" onClick={() => setSqlModalVisible(true)}>
              <Statistic
                title={
                  <Space>
                    <span>DDL语句数</span>
                    <Button 
                      type="link" 
                      size="small" 
                      style={{ padding: 0, height: 'auto' }}
                    >
                      点击查看详情
                    </Button>
                  </Space>
                }
                value={dbStats.totalDdlStatements || 0}
                prefix={<FileTextOutlined />}
                valueStyle={{ fontSize: 18, color: '#fa8c16', cursor: 'pointer' }}
              />
            </div>
            
            <div className="stat-item">
              <Text type="secondary">数据表数</Text>
              <div>
                <Text strong>{dbStats.totalTables || 0} 个</Text>
              </div>
            </div>
            
            <div className="stat-item">
              <Text type="secondary">处理状态</Text>
              <div>
                <Tag color="orange" icon={<CheckCircleOutlined />}>
                  {dbStats.completed ? '完成' : '处理中'}
                </Tag>
              </div>
            </div>
          </Card>
        </Col>

        <Col xs={24} lg={8}>
          <Card
            title={
              <Space>
                <SettingOutlined style={{ color: '#1890ff' }} />
                <span>综合统计</span>
              </Space>
            }
            className="statistics-card combined-card"
            size="small"
          >
            <div className="combined-stat">
              <div className="combined-stat-item">
                <div className="combined-count">
                  {(gitStats.totalSqlStatements || 0) + (dbStats.totalDdlStatements || 0)}
                </div>
                <div className="combined-label">总SQL语句</div>
              </div>
            </div>
            
            <Divider style={{ margin: '12px 0' }} />
            
            <div className="completion-rates">
              <div className="completion-item">
                <Text type="secondary">Git扫描</Text>
                <Progress 
                  percent={gitStats.completed ? 100 : task.progress || 0} 
                  size="small"
                  strokeColor="#52c41a"
                  showInfo={false}
                />
              </div>
              <div className="completion-item">
                <Text type="secondary">DB扫描</Text>
                <Progress 
                  percent={dbStats.completed ? 100 : task.progress || 0} 
                  size="small"
                  strokeColor="#fa8c16"
                  showInfo={false}
                />
              </div>
            </div>
          </Card>
        </Col>
      </Row>
    );
  };

  // 渲染默认统计（用于其他任务类型）
  const renderDefaultStatistics = (stats: any) => {
    return (
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Card
            title={
              <Space>
                <SettingOutlined style={{ color: '#1890ff' }} />
                <span>扫描统计</span>
              </Space>
            }
            className="statistics-card default-card"
          >
            <Row gutter={[16, 16]}>
              <Col xs={12} sm={6}>
                <div className="clickable-statistic" onClick={() => setSqlModalVisible(true)}>
                  <Statistic
                    title={
                  <Space>
                    <span>总SQL数</span>
                    <Button 
                      type="link" 
                      size="small" 
                      style={{ padding: 0, height: 'auto' }}
                    >
                      点击查看详情
                    </Button>
                  </Space>
                    }
                    value={stats.totalStatements || 0}
                    prefix={<FileTextOutlined />}
                    valueStyle={{ fontSize: 18, color: '#1890ff', cursor: 'pointer' }}
                  />
                </div>
              </Col>
              <Col xs={12} sm={6}>
                <Statistic
                  title="处理文件"
                  value={stats.totalFiles || 0}
                  prefix={<FileTextOutlined />}
                  valueStyle={{ fontSize: 18, color: '#52c41a' }}
                />
              </Col>
              <Col xs={12} sm={6}>
                <Statistic
                  title="有问题SQL"
                  value={problemStats.problemSqlCount}
                  prefix={<BugOutlined />}
                  valueStyle={{ 
                    fontSize: 18, 
                    color: problemStats.problemSqlCount > 0 ? '#ff4d4f' : '#52c41a' 
                  }}
                />
              </Col>
              <Col xs={12} sm={6}>
                <Statistic
                  title="问题率"
                  value={problemStats.problemRate.toFixed(1)}
                  suffix="%"
                  prefix={<WarningOutlined />}
                  valueStyle={{ 
                    fontSize: 18, 
                    color: problemStats.problemRate > 20 ? '#ff4d4f' : 
                           problemStats.problemRate > 10 ? '#faad14' : '#52c41a'
                  }}
                />
              </Col>
            </Row>
          </Card>
        </Col>
        
        {/* 问题统计卡片 */}
        {scanResults && (
          <Col span={24} style={{ marginTop: 16 }}>
            <Card
              title={
                <Space>
                  <WarningOutlined style={{ color: '#ff4d4f' }} />
                  <span>问题统计</span>
                </Space>
              }
              className="statistics-card problem-stats-card"
              size="small"
            >
              <Row gutter={[16, 16]}>
                <Col xs={12} sm={6}>
                  <Statistic
                    title="高危问题"
                    value={scanResults.issues?.filter(i => i.severity === 'HIGH').length || 0}
                    valueStyle={{ fontSize: 20, color: '#ff4d4f', fontWeight: 'bold' }}
                  />
                </Col>
                <Col xs={12} sm={6}>
                  <Statistic
                    title="中危问题"
                    value={scanResults.issues?.filter(i => i.severity === 'MEDIUM').length || 0}
                    valueStyle={{ fontSize: 20, color: '#faad14', fontWeight: 'bold' }}
                  />
                </Col>
                <Col xs={12} sm={6}>
                  <Statistic
                    title="低危问题"
                    value={scanResults.issues?.filter(i => i.severity === 'LOW').length || 0}
                    valueStyle={{ fontSize: 20, color: '#1890ff', fontWeight: 'bold' }}
                  />
                </Col>
                <Col xs={12} sm={6}>
                  <Statistic
                    title="总问题数"
                    value={scanResults.issues?.length || 0}
                    valueStyle={{ fontSize: 20, color: '#722ed1', fontWeight: 'bold' }}
                  />
                </Col>
              </Row>
            </Card>
          </Col>
        )}
      </Row>
    );
  };

  return (
    <div className="task-statistics">
      <div className="statistics-header">
        <Title level={4} style={{ margin: 0, color: '#1890ff' }}>
          任务统计信息
        </Title>
        <Text type="secondary" style={{ fontSize: 12 }}>
          {task.taskType === 'GIT_SCAN' && 'Git源码扫描统计'}
          {task.taskType === 'DATABASE_SCAN' && '数据库DDL扫描统计'}
          {task.taskType === 'MIXED_SCAN' && '混合扫描统计'}
          {!['GIT_SCAN', 'DATABASE_SCAN', 'MIXED_SCAN'].includes(task.taskType) && '任务执行统计'}
        </Text>
      </div>
      
      {parseStatistics()}
      
      {/* SQL语句详情弹窗 */}
      <SqlStatementsModal
        visible={sqlModalVisible}
        onClose={() => setSqlModalVisible(false)}
        taskId={task.id}
        taskName={task.taskName}
        scanResults={scanResults || null}
        taskConfig={task.config}
      />
    </div>
  );
};

export default TaskStatistics;